package com.kehongborui.servletinitparam;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-07-17
 */
@Deprecated
@WebServlet(urlPatterns = {"/login_", "/add_"}) // 标记
public class CookieOrSessionServlet extends HttpServlet {
    /**
     * 重写 http servlet doGet 方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.setAttribute("username", "rose");
        System.out.println(session.getAttribute("username"));
        // 获取客户端的所有 cookie
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName())) {
                // cookie 中中文解码
                System.out.println(URLDecoder.decode(cookie.getValue(), "UTF-8"));
            }
        }


        // 服务端创建cookie,这个cookie只能存储不超过4kb的数据,cookie 中不能直接存中文，如果非要放中，那必须对中文进行url 编码
        Cookie cookie = new Cookie("username", URLEncoder.encode("张彭洋明", "UTF-8"));
        // 设置cookie在浏览中保存的时间，单位是秒
        cookie.setMaxAge(5);
        // 将 cookie resp中
        resp.addCookie(cookie);

        PrintWriter writer = resp.getWriter();
        writer.println("看看cookie是否存在");
        writer.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置 客户端发过来的数据编码
        req.setCharacterEncoding("UTF-8");
        // 设置服务端响应的编码
        resp.setContentType("text/html;charset=UTF-8");

        // 获取客户端提交的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        if ("admin".equals(username) && "12345".equals(password)) {  // 登录成功
            // 将登录成功信息放到cookie
            Cookie cookie = new Cookie("username", username);
            resp.addCookie(cookie);
            // 登录成功，重定向到 登陆成功的页面
            resp.sendRedirect("loginSuccess");
        } else { // 登录失败的处理
            resp.getWriter().println("抱歉，登录失败");
        }
    }
}
